package com.aabte.cases;

import com.aabte.config.TestConfig;
import com.aabte.model.GetUserListCase;
import com.aabte.model.User;
import com.aabte.utils.DatabaseUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;

public class GetUserListTest {

    @Test(dependsOnGroups = "loginTrue", description = "获取性别为男的用户列表接口测试")
    public void getUserList() throws IOException {
        SqlSession session = DatabaseUtil.getSqlSession();
        GetUserListCase getUserListCase = session.selectOne("getUserInfoListCase", 1);
        System.out.println(getUserListCase);
        System.out.println(TestConfig.getUserListUrl);

        // 发送请求获取结果
        JSONArray jsonResult = getJsonResult(getUserListCase);

        // 验证
        List<User> userList = session.selectList(getUserListCase.getExpected(), getUserListCase);
        for (User user :
                userList) {
            System.out.println("获取的User：" + user.toString());
        }
        JSONArray userListJson = new JSONArray(userList);
        Assert.assertEquals(jsonResult.length(), userListJson.length());

        for (int i = 0; i < jsonResult.length(); i++) {
            JSONObject expect = (JSONObject) jsonResult.get(i);
            JSONObject actual = (JSONObject) userListJson.get(i);

            Assert.assertEquals(expect.get("id"), actual.get("id"));
            Assert.assertEquals(expect.get("username"), actual.get("username"));
            Assert.assertEquals(expect.get("password"), actual.get("password"));
            Assert.assertEquals(expect.get("sex"), actual.get("sex"));
            Assert.assertEquals(expect.get("age"), actual.get("age"));
            Assert.assertEquals(expect.get("permission"), actual.get("permission"));
            Assert.assertEquals(expect.get("isDelete"), actual.get("isDelete"));

            //Assert.assertEquals(expect.toString(), actual.toString());
        }


    }

    private JSONArray getJsonResult(GetUserListCase getUserListCase) throws IOException {

        HttpPost post = new HttpPost(TestConfig.getUserListUrl);
        JSONObject param = new JSONObject();
        param.put("username", getUserListCase.getUsername());
        param.put("sex", getUserListCase.getSex());
        param.put("age", getUserListCase.getAge());

        post.setHeader("Content-type", "application/json");

        StringEntity entity = new StringEntity(param.toString(), "utf-8");
        post.setEntity(entity);

        HttpResponse response = TestConfig.httpClient.execute(post);
        String result = EntityUtils.toString(response.getEntity());

        return new JSONArray(result);
    }

}
